#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


std::string DirName(const char* pwd)
{
  std::string dir = pwd;
  if(dir == "/")
    return "/";
  auto pos = dir.rfind("/");
  if(pos == std::string::npos)
    return "BUG?";
  return dir.substr(pos+1);
}

void ComLineProm()
{
  //printf("[%s@%s %s]$ ", getenv("USER"), getenv("HOSTNAME"), getenv("PWD"));

  printf("[%s@%s %s]# ", getenv("USER"), getenv("HOSTNAME"), DirName(getenv("PWD")).c_str());
}

bool WaitComLin(char* arg, size_t size)
{
  //因为别的函数也要用，所以得定义在主函数里
  //char arg[1024];

  //char *fgets(char *s, int size, FILE *stream);
  char* Flags = fgets(arg, size, stdin);
  if(Flags == NULL)
    return false;
  arg[strlen(arg)-1] = 0;
  if(strlen(arg) == 0)
    return false;
  return true;
}

int argc = 0;
char* argv[128];

void ComParse(char* arg)
{
  //别的函数也要用
  //int argc = 0;
  //char* argv[1024];
  argv[argc++] = strtok(arg, " ");
  while((bool)(argv[argc++] = strtok(nullptr, " ")));
  argc--;
}

int Execute()
{
  pid_t id = fork();
  if(id == 0)
  {
    execvp(argv[0], argv);
    exit(1);
  }

  pid_t rid = waitpid(id, nullptr, 0);
  (void)rid;
  return 0;
}

int main()
{
  while(true)
  {
    //打印命令行提示符
    //[zy@VM-20-12-centos myshell]$
    ComLineProm();
    //等待用户输入命令行转为字符串
    char arg[1024];
    WaitComLin(arg, sizeof(arg));
    
    //arg正常
    //printf("%s", arg);
    
    //命令行分析，转字符
    ComParse(arg);

    //检查分析
    //int i = 0;
    //for(auto x : argv)
    //{
    //  printf("argv[%d]->%s\n", i++, x);
    //}
    //执行命令
    Execute();

  }

  return 0;
}
